package com.ht.pms.core.controller.dataImport;

import com.ht.pms.core.common.cache.SalaryCodeBuilder;
import com.ht.pms.core.common.exception.ParamException;
import com.ht.pms.core.config.ExecutorPool;
import com.ht.pms.core.dao.DataImportDao;
import com.ht.pms.core.dao.SalaryUploadFileLogDao;
import com.ht.pms.core.dto.DataImportQueryReq;
import com.ht.pms.core.dto.PageResult;
import com.ht.pms.core.dto.QueryFileLogReq;
import com.ht.pms.core.dto.Result;
import com.ht.pms.core.dto.ReturnCodeEnum;
import com.ht.pms.core.dto.poi.SalaryUploadParam;
import com.ht.pms.core.dto.upload.UpLoadTemp;
import com.ht.pms.core.dto.upload.UploadFile;
import com.ht.pms.core.dto.upload.UploadFileLog;
import com.ht.pms.core.service.ImportLogService;
import com.ht.pms.core.service.SalaryExcelDataService;
import com.ht.pms.core.service.job.ThreadManager;
import com.ht.ussp.util.JsonUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

/**
 * @author:喻尊龙
 * @date: 2018/4/19
 */
//@CrossOrigin
@RestController
@RequestMapping("/dataImport")
public class DataImportController {

    private Logger logger = LoggerFactory.getLogger(DataImportController.class);
    private static final String SALARY_UPLOAD_PROCESS_CODE = "pms:salary:upload:process:";
    
    @Autowired
    private DataImportDao dataImportDao;
    @Autowired
    private SalaryUploadFileLogDao salaryUploadFileLogDao;
    
    @Autowired
    private SalaryExcelDataService salaryExcelDataService;
    
    @Autowired
    private ImportLogService importLogService;
    
    @Autowired
	private SalaryCodeBuilder salaryCodeBuilder;
    
    @Autowired
	private ThreadManager threadManager;

    @RequestMapping("/list")
    @ResponseBody
    public PageResult getDataImportList(DataImportQueryReq req){

        List<UploadFile> uploadFiles = dataImportDao.getUploadFileList(req);

        int count = dataImportDao.getUploadFileListCount(req);
        PageResult result = PageResult.success(uploadFiles,count);
        return  result;
    }

    @RequestMapping("/error")
    @ResponseBody
    public PageResult getDataImportRrrorList(QueryFileLogReq req){
        PageResult result = null;
        if(StringUtils.isBlank(req.getFileId())){
            result = PageResult.error(400,"参数为空");
            return  result;
        }
        try{
            List<UploadFileLog> uploadFileLog = salaryUploadFileLogDao.getUploadFileLog(req);
            int count = salaryUploadFileLogDao.getUploadFileLogCount(req);
            result = PageResult.success(uploadFileLog,count);
        }catch (Exception e){
            logger.error(e.getMessage());
            result = PageResult.error(500,"数据库操作异常"+e.getMessage());
        }

        return  result;
    }

    @RequestMapping("/delete")
    @ResponseBody
    public Result delete(@RequestParam("fileId") String fileId, @RequestParam("batchCode") String batchCode){
        Result result = Result.buildSuccess();
        try{
            result = importLogService.deleteImportData(fileId,batchCode);
        }catch (Exception e){
            logger.error(e.getMessage());
            result = Result.buildFail("删除失败："+e.getMessage());
        }
        return  result;
    }

    @RequestMapping("/newImportData")
    @ResponseBody
    public Result getNewImportFile(){
        Result result = Result.buildSuccess();
        try {
            result = importLogService.getNewImportData();
        }catch (Exception e){
            logger.error(e.getMessage());
            result = Result.buildFail();
        }
        return result;
    }

    @RequestMapping("/checkImportData")
    @ResponseBody
    public Result checkImportData(@RequestParam("fileId") String fileId,@RequestParam("batchCode") String batchCode){
        Result result = Result.buildSuccess();
        try{
           int count =  dataImportDao.getFailImportCount(fileId,batchCode);
           if(count>0){
                result = Result.buildFail();
           }
        }catch (Exception e){
            logger.error(e.getMessage());
            result = Result.buildFail().msg("数据库操作异常："+e.getMessage());
        }
        return  result;
    }

    @RequestMapping("/updataCheckState")
    @ResponseBody
    public Result updataCheckState(@RequestParam("fileId") String fileId,@RequestParam("batchCode") String batchCode,@RequestParam("templateCode") String templateCode){
        Result result = Result.buildSuccess();
        try{
            importLogService.checkDate(fileId,batchCode,templateCode);
        }catch (Exception e){
            logger.error(e.getMessage());
            result = Result.buildFail().msg("数据库操作异常："+e.getMessage());
        }
        return  result;
    }

    @PostMapping("/uploadErrorFile")
	public Result upNewSalaryTable(@ModelAttribute SalaryUploadParam req, HttpServletRequest request) throws Exception {
    	logger.info("[上传错误数据]上传错误数据，  param:[{}]", req);
    	if (req.getFile() == null) {
    		logger.error("[导入基础数据] 请求参数导入文件为空！");
			throw new ParamException(ReturnCodeEnum.ERROR_PARAM.getReturnCode(),
					ReturnCodeEnum.ERROR_PARAM.getCodeDesc() + ": file");
		}
    	// 生成内部处理批次号
		Long processCode = salaryCodeBuilder.generateDailyCode(SALARY_UPLOAD_PROCESS_CODE);
		String originalFilename = req.getFile().getOriginalFilename();
		req.setFileName(originalFilename.substring(0, originalFilename.lastIndexOf(".")));
		
		req.setInputStream(req.getFile().getInputStream());
		ExecutorPool.cachedThreadPool.execute(threadManager.createExcelImportThread(req, processCode));
		return Result.buildSuccess(processCode);
	}




}
